package com.lly.schedule.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lly.schedule.common.Result;
import com.lly.schedule.common.ResultCodeEnum;
import com.lly.schedule.pojo.SysSchedule;
import com.lly.schedule.pojo.SysUser;
import com.lly.schedule.serice.SysScheduleService;
import com.lly.schedule.serice.SysUserService;
import com.lly.schedule.serice.impl.SysUserServiceImpl;
import com.lly.schedule.util.MD5Util;
import com.lly.schedule.util.WebUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.HashMap;

@WebServlet("/user/*")
public class SysUserController extends BaseController {
    private SysUserService sysUserService = new SysUserServiceImpl();

    /**
     * 业务处理方法(接口)
     * @param req
     * @param resp
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysUser sysUser1 = WebUtil.readJson(req, SysUser.class);
        int rows= 0;
        try {
            rows = sysUserService.addUser(sysUser1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Result result= Result.ok(null);
        if (rows>1){
            result=Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp,result);
    }
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysUser sysUser1 = WebUtil.readJson(req, SysUser.class);
        SysUser sysUser=sysUserService.login(sysUser1.getUsername());

        Result result=null;
        if(sysUser==null){
            result=Result.build(result, ResultCodeEnum.USERNAME_USED);
        }else if(!sysUser.getUserPwd().equals(MD5Util.encrypt(sysUser1.getUserPwd()))){
            result=Result.build(result, ResultCodeEnum.PASSWORD_ERROR);
        }else{
            HashMap map=new HashMap<>();
            sysUser.setUserPwd(null);
            map.put("loginUser",sysUser);

             result= Result.ok(map);
        }
        WebUtil.writeJson(resp, result);
    }
    protected void checkUserPwd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        SysUser login = sysUserService.login(username);
        Result result= Result.ok(null);
        if(login!=null){
            result=Result.build(null,ResultCodeEnum.USEDRNAME);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(json);
    }
}
